package com.bw.miaosha.controller;

import java.util.*;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.miaosha.conf.AlipayConfig;
import com.bw.miaosha.dao.GoodsDao;
import com.bw.miaosha.dao.MiaoshaActivityDao;
import com.bw.miaosha.entity.GoodsEntity;
import com.bw.miaosha.entity.MiaoshaActivityEntity;
import com.bw.miaosha.entity.MiaoshaOrderEntity;
import com.bw.miaosha.service.GoodsService;
import com.bw.miaosha.service.MiaoshaActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.bw.miaosha.entity.OrderInfoEntity;
import com.bw.miaosha.service.OrderInfoService;
import com.bw.common.utils.PageUtils;
import com.bw.common.utils.R;

import javax.servlet.http.HttpServletRequest;


/**
 * 
 *
 * @author zhucaiyi
 * @email zhucaiyi@gmail.com
 * @date 2022-02-22 11:27:06
 */
@Controller
@RequestMapping("miaosha/orderinfo")
public class OrderInfoController {
    @Autowired
    private OrderInfoService orderInfoService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = orderInfoService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @ResponseBody
    public R info(@PathVariable("id") String id){
		OrderInfoEntity orderInfo = orderInfoService.getById(id);

        return R.ok().put("orderInfo", orderInfo);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @ResponseBody
    public R save(@RequestBody OrderInfoEntity orderInfo){
		orderInfoService.save(orderInfo);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @ResponseBody
    public R update(@RequestBody OrderInfoEntity orderInfo){
		orderInfoService.updateById(orderInfo);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @ResponseBody
    public R delete(@RequestBody Long[] ids){
		orderInfoService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    @RequestMapping("alipay")
    @ResponseBody
    public String goFu(@RequestParam String orderId) throws Exception {
        //查询订单
        OrderInfoEntity order = orderInfoService.getById(orderId);

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(order.getId().getBytes(),"UTF-8");
        //付款金额，必填
        String total_amount = new String(order.getGoodsPrice().toString().getBytes(),"UTF-8");
        //订单名称，必填
        String subject = new String(order.getGoodsName().getBytes(),"UTF-8");
        //商品描述，可空
        String body = new String(order.getGoodsName().getBytes(),"UTF-8");
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        //输出
        return result;
    }

    @Autowired
    private MiaoshaActivityDao miaoshaActivityDao;

    @Autowired
    private MiaoshaActivityService miaoshaActivityService;

    @Autowired
    private GoodsService goodsService;

    @RequestMapping("success")
    public String success(HttpServletRequest request) throws Exception {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        String id = params.get("out_trade_no");
        OrderInfoEntity byId = orderInfoService.getById(id);
        byId.setPayDate(new Date());
        byId.setStatus(1);
        Long goodsId1 = byId.getGoodsId();
        QueryWrapper<MiaoshaActivityEntity> goodsId = new QueryWrapper<MiaoshaActivityEntity>().eq("goods_id", goodsId1);
        MiaoshaActivityEntity one = miaoshaActivityDao.selectOne(goodsId);
        GoodsEntity byId1 = goodsService.getById(one.getGoodsId());
        byId1.setGoodsStock(byId1.getGoodsStock()-1);
        goodsService.updateById(byId1);
        boolean b = orderInfoService.updateById(byId);

            return "redirect:http://127.0.0.1:5500/orderList.html";

    }

}
